package cc.kzc.adminauth.misc;

import javax.servlet.http.HttpServletRequest;

public class HttpRequestUtil {

	public static final String UNKNOWN = "unknown";

	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-real-ip");// 先从nginx自定义配置获取
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static String getProto(HttpServletRequest request) {
		String proto = request.getHeader("X-Forwarded-Proto"); // 先获取标准的
		
		return proto;
	}
	
	public static String getHost(HttpServletRequest request) {
		String host_port = getHostPort(request); // 先获取标准的
		if (host_port == null || host_port.length() == 0) {
			return null;
		}
		String[] hp = host_port.split(":");
		
		return hp[0];
	}
	
	public static String getPort(HttpServletRequest request) {
		String host_port = getHostPort(request); // 先获取标准的
		if (host_port == null || host_port.length() == 0) {
			return null;
		}
		String[] hp = host_port.split(":");
		if (hp.length > 1) {
			return hp[1];
		}
		return null;
	}
	
	public static String getHostPort(HttpServletRequest request) {
		String host_port = request.getHeader("Host"); // 先获取标准的
		if (host_port == null || host_port.length() == 0) {
			host_port = request.getHeader("X-Forwarded-Host");
		}
		return host_port;
	}
	
}
